package com.rainfull.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.rainfull.ui.R;
import com.rainfull.core.RAPItemInfo;
import com.rainfull.core.IRUIAPNotify;
import com.rainfull.core.RAPMgr;
import com.rainfull.core.RNetworkProcess;
import com.rainfull.core.RUploadApResult;
import com.rainfull.core.WifiHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout.LayoutParams;

public class RUIApList extends Activity implements IRUIAPNotify, OnItemClickListener 
{
    private int m_nAPState; //上一次的wifi状态
    public ArrayList<HashMap<String, Object>> m_aplist = null;
    //private RUIGMap m_gMap = null;
    private main m_mainActive = null;
    private RAPMgr m_APMgr = null;
    private boolean	m_bInitOk = false;
    private boolean	m_bInActive = false;    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ap_list);
        m_mainActive = (main)this.getParent();
        m_aplist = m_mainActive.m_aplist;
        LinearLayout ll = (LinearLayout) findViewById(R.id.ap_list_ll_1);
        ll.setLayoutParams(new LayoutParams(m_mainActive.getScreenWidth(), 
        		LayoutParams.FILL_PARENT));
        m_APMgr = new RAPMgr(this, this);    
        m_mainActive.m_strImei = m_APMgr.getImei();
        m_nAPState = m_APMgr.getWifiState();
        init();
        if (m_nAPState == WifiManager.WIFI_STATE_DISABLED ||
        		m_nAPState == WifiManager.WIFI_STATE_DISABLING)
        {
        	m_mainActive.changeTabView(RUIApList.class, RUIApEnable.class);        	
        }
        m_bInActive = true;
        //test();
    }  
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        return false;
    }
    @Override
    public void onPause()
    {
    	m_bInActive = false;
    	super.onPause();    	
    }
    @Override
    public void onResume()
    {    	
    	super.onResume();
    	m_bInActive = true;
    }
    
    public void test()
    {
    	//m_mainActive.getUserScore();
    	//m_mainActive.subUserScore(1);
    	//int ccc = m_mainActive.getUserScore();
    	//int ddd = m_mainActive.getUserScore();
    	/*ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);   
        NetworkInfo[] netinfo = connec.getAllNetworkInfo();
        int aaa = connec.getNetworkPreference();
        connec.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
        int bbb = connec.getNetworkPreference();
        for (int i = 0; i < netinfo.length; i++)
        {
        	NetworkInfo item = netinfo[i];
        	int fff = 0;
        }   */ 	
    }
    
    public void init()
    {    	
    	//初始化ap列表
    	initApList();    	
    	m_bInitOk = true;
    	AddFindTipToList();
    }
  //更新ap列表
    public void initApList()
    {
    	ListView list = (ListView) findViewById(R.id.ap_list_list_wifi);
    	//去掉横线
    	list.setDividerHeight(0);
    	//生成适配器的Item和动态数组对应的元素  
        SimpleAdapter listItemAdapter = new SimpleAdapter(this, m_aplist,//数据源   
            R.layout.list_items,//ListItem的XML实现  
            //动态数组与ImageItem对应的子项          
            new String[] {"level", "ssid", "state", "lock"},   
            //ImageItem的XML文件里面的一个ImageView,两个TextView ID  
            new int[] {R.id.list_items_img_level, R.id.list_items_text_ssid, 
        		R.id.list_items_text_apstate, 
        		R.id.list_items_img_state}  
        );           
        //添加并且显示  
        list.setAdapter(listItemAdapter);
        //添加点击
        list.setOnItemClickListener(this);
    }
    public void onItemClick(AdapterView<?> arg0, View arg1, int nIndex, long arg3) 
    {
    	HashMap<String, Object> itemInfo = m_aplist.get(nIndex);
    	//如果是提示信息，没有任何作用
    	if (isTipItem(itemInfo.get("bssid").toString()) == true)
    	{
    		return;
    	}
    	else
    	{
    		if (m_mainActive.getUserScore() <= 0)
			{
    			int nAddGold = -m_mainActive.getUserScore();
    			m_mainActive.addUserScore(nAddGold);    			
    			//Toast.makeText(RUIApList.this, "你已经超过最大试用次数，请注册并登陆后，再使用！", Toast.LENGTH_LONG).show();
    			//return;
			}
    		ScanResult scanItem = (ScanResult)itemInfo.get("scanResult");
		    if (Integer.parseInt(itemInfo.get("open").toString()) == 1 ||//公开的ap不要密码
		    	//itemInfo.get("pwd").toString().length() > 0) //有密码了
		    	itemInfo.get("conn_state").toString().equals("1") || //已经连接了
		    	new Integer(itemInfo.get("lock").toString()) == R.drawable.key || //状态是钥匙
		    	new Integer(itemInfo.get("lock").toString()) == R.drawable.pay) //状态时pay
		    {
		    	
		    	if (itemInfo.get("conn_state").toString().equals("1") == true)
		    	{
		    		int nLevel = scanItem.level;
		    		WifiInfo wifiInfo = m_APMgr.getCurrConn();
		    		String strDebug = GetApDesInfo(wifiInfo.getNetworkId(), nLevel);
		    		if (strDebug.length() > 0)
			    	{
		    			new AlertDialog.Builder(this).
				    	setTitle("无线热点详情").
		        		setPositiveButton("确定", new DialogInterface.OnClickListener() 
		        		{
		                    public void onClick(DialogInterface dialog, int whichButton) 
		                    {
		                    	dialog.cancel();                    
		                    }
		                }).
		        		setMessage(strDebug).show();
				    	return;
			    	}
		    	}    			
		    	String strPwd = "";
		    	if(itemInfo.get("pwd").toString().length() > 0)
		    	{
		    		strPwd = itemInfo.get("pwd").toString();
		    	}
		    	updateApConnState(itemInfo, getText(R.string.ap_conning).toString());
				boolean bRet = m_APMgr.ConnToAp((ScanResult)itemInfo.get("scanResult"), strPwd);
				if (bRet == false && Integer.parseInt(itemInfo.get("open").toString()) != 1)
				{    
					//弹出密码提示窗口
	                //TODO需要判断是否是OPENWIFI，如果是则不需要弹出提示，直接连接就OK
	                ShowApConnDlg(scanItem.BSSID, scanItem.SSID, 
	    	    			Integer.parseInt(itemInfo.get("level").toString()), 
	    	    			"", "密码验证错误，请重新输入密码");    	                         				
				}
		    }
		    else
			{
		    	//todo需要判断是否是openwifi，如果是则不需要弹出提示，直接连接就ok
		    	ShowApConnDlg(scanItem.BSSID, scanItem.SSID, 
		    			Integer.parseInt(itemInfo.get("level").toString()), 
		    			itemInfo.get("pwd").toString(), "");	    	    	
			}
    	}
	}
    /*
     * 显示ap连接对话框
     */
    public void ShowApConnDlg(String strBSSID, String strSSID, 
			int nLevel, String strPwd, String strDes)
	{
    	Intent intent = new Intent(RUIApList.this, RUIAPConnDlg.class);        		
		intent.putExtra("pwd", strPwd);        		
        intent.putExtra("bssid", strBSSID);
        intent.putExtra("ssid", strSSID);
        intent.putExtra("level", nLevel);
        intent.putExtra("des", strDes);
        intent.putExtra("login", m_mainActive.IsUserLogin());
         //弹出密码提示窗口
        //todo需要判断是否是openwifi，如果是则不需要弹出提示，直接连接就ok
        startActivityForResult(intent, 2);
	}
    //list中当前item是否是提示
    public boolean isTipItem(String strBSSID)
    {
    	if (strBSSID.equals("-1") ||
    		strBSSID.equals("-2"))
    		return true;
    	else
    		return false;
    }
    public void AddFindTipToList()
    {
    	//增加一个搜索无线网络的提示
    	addItemToList("-1", "正在搜索无线网络...", -1, 
        			"", null, -1, -1);
    }
    public void AddNoApTipToList()
    {
    	//增加一个搜索无线网络的提示
    	addItemToList("-2", "周围没有无线网络", -1, 
    			"", null, -1, -1);
    }
    public void RemoveTipToList()
    {
    	int nSize = m_aplist.size();
    	if (nSize > 0)
    	{    		
    		HashMap<String, Object> mapItem = m_aplist.get(nSize - 1);
    		if (isTipItem(mapItem.get("bssid").toString()))
    		{
    			m_aplist.remove(nSize - 1);
    		}
    	}
    	refreshListView();
    }    
    /*
     * list中增加一项
     */
    
    public HashMap<String, Object> addItemToList(String strBSSID, String strSSID, 
			int nLevelImgId, String strPwd, ScanResult scanItem, int nOpen, int nPay)
	{    	    	
    	if (strPwd == null)
    		strPwd = "";
		WifiInfo currWifiInfo = m_APMgr.getConnConfigInfo();
		HashMap<String, Object> mapItem = null;
		boolean bFind = false;
		for(int i=0; i< m_aplist.size(); i++)
		{	        		        		
			ScanResult scanHaveFind = (ScanResult)m_aplist.get(i).get("scanResult");			
			if (scanHaveFind.BSSID.equals(strBSSID) ||
				scanHaveFind.SSID.equals(strSSID))
			{   
				bFind = true;
				mapItem = m_aplist.get(i); 
				break;
			}
		}		
		if (mapItem != null)
		{
			int nLevel = new Integer(mapItem.get("level").toString());
			if (nLevelImgId > nLevel)
			{	
				mapItem.put("level", nLevelImgId);
				mapItem.put("ssid", strSSID);
				mapItem.put("bssid", strBSSID);
				mapItem.put("level", nLevelImgId);
				mapItem.put("pay", nPay);
				
				if (strPwd.length() > 0 ||
					mapItem.get("pwd") == null)
				{
					mapItem.put("pwd", strPwd);
				}
				mapItem.put("scanResult", scanItem);
				mapItem.put("open", nOpen);
			}
		}
		else
		{
			mapItem = new HashMap<String, Object>();
			mapItem.put("ssid", strSSID);
			mapItem.put("bssid", strBSSID);
			mapItem.put("level", nLevelImgId);
			if (strPwd.length() > 0 ||
				mapItem.get("pwd") == null)
			{
				mapItem.put("pwd", strPwd);
			}		
			mapItem.put("conn_state", 0);
			mapItem.put("scanResult", scanItem);
			mapItem.put("open", nOpen);
			mapItem.put("des", "这个一个测试的ap");	
			mapItem.put("lock", -1);
			mapItem.put("token", "");
			mapItem.put("pay", nPay);
			if (currWifiInfo != null &&
				currWifiInfo.getBSSID() != null &&
				currWifiInfo.getBSSID().equals(strBSSID))
		    {	
				//当前热点的密码
				String strCurPwd = m_APMgr.getCfgPwdByNetWorkId(currWifiInfo.getNetworkId());
				mapItem.put("pwd", strCurPwd);
		    	mapItem.put("state", getText(R.string.ap_cur_conn).toString());
		    	
		    	ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		    	NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		    	if (mWifi.isConnected()) 
		    	{
		    		mapItem.put("conn_state", 1);
		    	}
		    	else
		    	{
		    		switch(mWifi.getDetailedState()) 
		            {    	  
		            	case CONNECTING:
		            		mapItem.put("state", getText(R.string.ap_conning).toString()); 		            		
		            		break;
		                case DISCONNECTED:
		                	mapItem.put("state", getText(R.string.ap_disconn).toString());             		
		                	break;
		                case SCANNING:		                	 
		                     break;
		                case OBTAINING_IPADDR:
		                	mapItem.put("state", getText(R.string.ap_get_ip).toString());
		                	break;
		            }    
		    	}
		    }
			else if(isTipItem(strBSSID) == false && bFind == false)
			{
				if(nOpen == 1)
				{
					mapItem.put("state", "");
					if (nPay == 1)
						mapItem.put("lock", R.drawable.pay);
					else
						mapItem.put("lock", R.drawable.key);
				}
				else
					mapItem.put("state", getText(R.string.ap_find_pwd).toString());
			}
		}
		if (bFind == false)
		{
			m_aplist.add(mapItem);
			refreshListView();
			if (nOpen == 0 && strBSSID.equals("-1") == false)
			{
				mapItem.put("token", m_mainActive.m_userInfo.getToken());
				new RUIGetApDesInfoBySvrTask().execute(mapItem);
			}
		}
		return mapItem;
	}
    /*
	 * 监听账号密码输入对话框
	 */
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {  
    	 switch (requestCode)
    	 {
    	 	case 2:	//ap连接对话框
		  		if (resultCode == RESULT_OK)
		  		{
		  			String strPwd = data.getStringExtra("pwd");
		  			String strBSSID = data.getStringExtra("bssid");
		  			int nShare = data.getIntExtra("share", 1);
		  			HashMap<String, Object> itemInfo = getListItemByBSSID(strBSSID);
		  			if (itemInfo != null)
		  			{
		  				WifiHelper helper = new WifiHelper();
		  				updateApConnState(itemInfo, getText(R.string.ap_conning).toString());
		  				itemInfo.put("share", nShare);
	        			boolean bRet = m_APMgr.ConnToAp((ScanResult)itemInfo.get("scanResult"), strPwd);	        	        			
	        			if (bRet == false)
	        			{
	        				updateApConnState(itemInfo, getText(R.string.ap_error_pwd).toString());
	        			}
	        			else
	        			{
	        				itemInfo.put("pwd", strPwd);
	        				refreshListView();
	        			}
		  			}
		  		}
		  	break;
    	 	case 1:	//wifi连接对话框
    	 	{
    	 		int nEnable = data.getIntExtra("enable", -1);
	  			if (nEnable == 1)
	  			{
	  				//m_APMgr.scanAp();
	  			}
    	 	}
    	 	break;
    	  };    	 
    }
    
    public HashMap<String, Object> getListItemByBSSID(String strBSSID)
    {
    	if (strBSSID != null && strBSSID.length() > 0 && m_aplist != null)
    	{
    		for(int i = 0; i < m_aplist.size(); i++)    	
			{
				HashMap<String, Object> itemTemp = m_aplist.get(i);
				ScanResult scanResult = (ScanResult)itemTemp.get("scanResult");
				if (scanResult != null && scanResult.BSSID.equals(strBSSID))
				{
					return itemTemp;					
				}
			}	    	
    	}
    	return null;
    }
    
    /*
     * ap数据变化的通知
     * @see com.rainfull.core.IRUIAPNotify#onWifiStateChanged(int)
     */
	public void onWifiStateChanged(int nState)
    {
    	if (m_bInitOk == false)
    		return;
    	switch(nState)
    	{
	    	case WifiManager.WIFI_STATE_ENABLED:    		
			    {        	
		    		//todo需要放在资源里，考虑多语言版本
			    	m_APMgr.scanAp();
			    }
			    break;
	    	case WifiManager.WIFI_STATE_ENABLING:
			    {        	
		    		//todo需要放在资源里，考虑多语言版本
			    }
			    break;
	    	case WifiManager.WIFI_STATE_DISABLING: 
			    {        	
		    		//todo需要放在资源里，考虑多语言版本
			    }
			    break;
	    	case WifiManager.WIFI_STATE_DISABLED:
			    {
			    	m_mainActive.changeTabView(RUIApList.class, RUIApEnable.class);
			    }
			    break;
    	}
    }
    /*
     * 更新ap连接状态
     */
    public void updateApConnState(String strBSSID, String strState)
    {
    	HashMap<String, Object> itemInfo = getListItemByBSSID(strBSSID);
    	updateApConnState(itemInfo, strState);
    }
    /*
     * 更新ap连接状态
     */
    public void updateApConnState(int nIndex, String strState)
    {
    	HashMap<String, Object> itemInfo = m_aplist.get(nIndex);
    	updateApConnState(itemInfo, strState);		 	
    }
    public void updateApConnState(HashMap<String, Object> itemInfo, String strState)
    {    
    	if (itemInfo != null)
		{
	    	for(int i = 0; i < m_aplist.size(); i++)    	
			{
	    		HashMap<String, Object> itemTemp = m_aplist.get(i);
	    		if (itemTemp.get("bssid").toString().equals(itemInfo.get("bssid").toString()) &&
	    			strState.length() > 0)
	    		{
	    			itemTemp.put("state", strState);
	    			itemTemp.put("lock", -1);
	    		}
	    		else
	    		{	
	    			itemTemp.put("state", "");
	    			itemTemp.put("conn_state", 0);
	    			if (Integer.parseInt(itemTemp.get("open").toString()) == 1 ||
	    				itemTemp.get("pwd").toString().length() > 0)
	    				if (Integer.parseInt(itemTemp.get("pay").toString()) == 1)
	    					itemTemp.put("lock", R.drawable.pay);
	    				else
	    					itemTemp.put("lock", R.drawable.key);
	    			else
	    				itemTemp.put("lock", R.drawable.lock);
	    		}
	    		
			}
		}
    	refreshListView();    	
    }
    
    /*
     *ap的连接状态发生变化 
     */
    public void onApConnStateChange(NetworkInfo networkInfo, String strBSSID)
    {    	
    	final NetworkInfo.DetailedState detailed = networkInfo.getDetailedState();
    	switch(detailed) 
        {    	  
        	case CONNECTING:
        		updateApConnState(strBSSID, getText(R.string.ap_conning).toString());	        	
	        	break;
            case DISCONNECTED:
            	updateApConnState(strBSSID, getText(R.string.ap_disconn).toString());            		
            	break;
            case SCANNING:
                    return;
            case OBTAINING_IPADDR:
            	updateApConnState(strBSSID, getText(R.string.ap_get_ip).toString());            	
            	break;
            case CONNECTED:
            	{   
            		
            		String strPwd = "";
            		//从用户输入的密码框中获取密码
            		for(int i=0; i< m_aplist.size(); i++)
            		{	        		        		
            			ScanResult scanHaveFind = (ScanResult)m_aplist.get(i).get("scanResult");			
            			if (scanHaveFind != null && 
            				scanHaveFind.BSSID.equals(strBSSID) &&
            				m_aplist.get(i).get("pwd") != null &&
            				m_aplist.get(i).get("pwd").toString().length() > 0)
            			{   
            				strPwd = (String)m_aplist.get(i).get("pwd");            				
            				break;
            			}
            		}
            		WifiInfo wifiInfo = m_APMgr.getCurrConn();
            		if (wifiInfo != null)
            		{
            			
            			String strProfilePwd = m_APMgr.getCfgPwdByNetWorkId(wifiInfo.getNetworkId());
            			if (strProfilePwd.equals("*") == false)
            				strPwd = strProfilePwd;            			
            		}
            		
            		if (strPwd != null && 
            			strPwd.length() > 0)
            		{            			            			
            			HashMap<String, Object> itemInfo = getListItemByBSSID(strBSSID);
            			if (itemInfo != null)
            			{
            				itemInfo.put("pwd", strPwd);
            				itemInfo.put("lock", R.drawable.key);
            				itemInfo.put("conn_state", 1);
            				itemInfo.put("token", m_mainActive.m_userInfo.getToken());
            				if (itemInfo.get("share") == null)
            					itemInfo.put("share", 1);
            				//共享了，就上传密码
            				if (itemInfo.get("share").toString().equals("1"))
            				{
            					new RUIUpoladApInfoToSvrTask().execute(itemInfo);
            				}
            				//没有登录直接显示当前积分信息
            				if(m_mainActive.IsUserLogin() == 0 &&
            					m_mainActive.getUserScore() > 0)
            				{
            					m_mainActive.addUserScore(-1);
            					if (m_bInActive == true)
            						Toast.makeText(RUIApList.this, "你当前还有剩余积分:"+m_mainActive.getUserScore()+"分", Toast.LENGTH_LONG).show();
            				}            				
            			}            			
            		}
            		
            		
            		updateApConnState(strBSSID, getText(R.string.ap_cur_conn).toString());            		
            	}
            	break;
            case FAILED:
            	{
            		updateApConnState(strBSSID, getText(R.string.ap_conn_failed).toString());            		
            	}            	
            	break;
        }
    }   
    /*
     * ap扫描回调函数
     */
    public void onScanResult(List<ScanResult> aplist)
    {    	    
    	if (m_bInitOk == false || aplist == null)
    		   return;
    			
    	//显示ap列表
    	boolean bNewFind = false;
        for(int i=0; i<aplist.size(); i++)
        {          	
        	ScanResult scanItem = aplist.get(i);
        	int nLevelImgId = 0;
        	if(scanItem.level > -70)
        		nLevelImgId = R.drawable.ap_level_4;
            else if(scanItem.level > -80)
            	nLevelImgId = R.drawable.ap_level_3;
            else if(scanItem.level > -90)
            	nLevelImgId = R.drawable.ap_level_2;
            else
            	nLevelImgId = R.drawable.ap_level_1;
        	int nOpen = -1;
        	String security = WifiHelper.getScanResultSecurity(scanItem);
            if(security.equals(WifiHelper.OPEN))	
    	    	nOpen = 1;  	    	
    	    else
    	    	nOpen = 0;
            int nPay = 0;
            //默认下面的是选项为收费的ap
            if(scanItem.SSID.equalsIgnoreCase("cmcc")||
               scanItem.SSID.equalsIgnoreCase("chinanet")||
               scanItem.SSID.equalsIgnoreCase("chinaunicom"))	
            {
            	nPay = 1;  	    	
            }
    	    RemoveTipToList();
            HashMap<String, Object> itemInfo = addItemToList(scanItem.BSSID, scanItem.SSID, nLevelImgId, 
        			"", scanItem, nOpen, nPay);
            uploadOpenApp(itemInfo);
        }     
        RemoveTipToList();
        //周围没有无线网络
        if (m_aplist.size() == 0)
        {
        	AddNoApTipToList();
        }
    }   
    /*
     * 后台上报免费的ap
     */
    public boolean uploadOpenApp(HashMap<String, Object> itemInfo)
    {    	
    	if (itemInfo == null || 
    		itemInfo.get("open") != null ||
    		itemInfo.get("pay") != null ||
    		Integer.parseInt(itemInfo.get("open").toString()) == 0 || 
    		Integer.parseInt(itemInfo.get("pay").toString()) == 1)
    	{	
    		return false;
    	}
    	new RUIUpoladApInfoToSvrTask().execute(itemInfo);
    	return true;
    }
    /*
     * 刷新ap列表
     */
    public void refreshListView()
    {
    	ListView list = (ListView) findViewById(R.id.ap_list_list_wifi); 
    	SimpleAdapter listItemAdapter = (SimpleAdapter)list.getAdapter();
    	if (listItemAdapter != null)
    		listItemAdapter.notifyDataSetChanged();
    }
    
  //后台上传账号密码信息
	public class RUIUpoladApInfoToSvrTask extends AsyncTask
	{
		@Override
		protected Object doInBackground(Object... param) 
		{						
			HashMap<String, Object> itemInfo = (HashMap<String, Object>)param[0];
			if (itemInfo == null || itemInfo.get("bssid") == null ||
				itemInfo.get("pwd") == null || itemInfo.get("ssid") == null)
				return null;
			RAPItemInfo apItemInfo = new RAPItemInfo();
			apItemInfo.setBSSID(itemInfo.get("bssid").toString());
			apItemInfo.setPwd(itemInfo.get("pwd").toString());
			apItemInfo.setSSID(itemInfo.get("ssid").toString());
			if (itemInfo.get("pwd").toString().equals("*"))
			{
				Toast.makeText(RUIApList.this, "错误的无线密码*", Toast.LENGTH_LONG).show();
				return null;
			}
			else
			{
				String strToken = "";
				if (itemInfo.get("token") != null)
					strToken = itemInfo.get("token").toString();
				Integer nShare = Integer.parseInt(itemInfo.get("share").toString());
				RUploadApResult retInfo = RNetworkProcess.upLoadSvrApPwd(strToken, nShare, apItemInfo);
				return retInfo;
			}			
		}
		protected void onPostExecute(Object result) 
		{  			
			if (result == null)
				return;
			RUploadApResult retInfo = (RUploadApResult)result;
			Integer nScore = (Integer)retInfo.getUserScore();
			if (nScore != -1)
			{
				if (m_mainActive.IsUserLogin() == 1)
				{
					if (nScore > 0)
						m_mainActive.m_userInfo.setScore(nScore);
					if (m_bInActive == true)
						Toast.makeText(RUIApList.this, "上传无线信息成功!,当前积分："+m_mainActive.m_userInfo.getScore(), Toast.LENGTH_LONG).show();
				}				
			}
			else if (nScore == -1)
			{
				m_mainActive.saveUploadFailedApInfo(retInfo.getUrlUpLoad());
				//if (m_bInActive == true)
				//	Toast.makeText(RUIApList.this, "上传ap信息失败!", Toast.LENGTH_LONG).show();
			}			
		}
	}
	
	//后台获取账号密码信息
	public class RUIGetApDesInfoBySvrTask extends AsyncTask
	{
		@Override
		protected Object doInBackground(Object... param) 
		{
			HashMap<String, Object> mapItem = (HashMap<String, Object>)param[0];
			List<RAPItemInfo> listApInfo = new ArrayList<RAPItemInfo>();			
			RAPItemInfo apItemInfo = new RAPItemInfo();		
			apItemInfo.setBSSID(mapItem.get("bssid").toString());
			if (mapItem.get("open") != null&&
				Integer.parseInt(mapItem.get("open").toString()) != 1 &&
				mapItem.get("pwd") != null &&	
				mapItem.get("pwd").toString().length() == 0)	//如果没有密码就再查找一次
				listApInfo.add(apItemInfo);
			String strToken = "";
			if (mapItem.get("token") != null)
				strToken = mapItem.get("token").toString();
			RNetworkProcess.getApPwdFromSvr(strToken, listApInfo);
			return listApInfo;
		}
		protected void onPostExecute(Object result) 
		{  
			List<RAPItemInfo> listApInfo = (List<RAPItemInfo>)result;
			for (int i = 0; i < listApInfo.size(); i++)
			{
				RAPItemInfo apItemInfo = listApInfo.get(i);
				String strBSSID = apItemInfo.getBSSID();
				//不是正在连接的网络
				HashMap<String, Object> itemTemp = null;
				for (int j = 0; j < m_aplist.size(); j++)				
				{				
					itemTemp = m_aplist.get(j);
					String strBSSIDTemp = itemTemp.get("bssid").toString();
					if (strBSSID.equals(strBSSIDTemp))
					{
						itemTemp.put("state", "");
						if (apItemInfo.getPwd().length() != 0)
						{
							//找到密码
							itemTemp.put("pwd", apItemInfo.getPwd());
							itemTemp.put("lock", R.drawable.key);
						}
						else
						{
							//找到密码
							itemTemp.put("pwd", apItemInfo.getPwd());
							itemTemp.put("lock", R.drawable.lock);
						}
						break;
					}
				}						
			}
			//刷新视图信息
			refreshListView();
		}
	}
	public String GetApDesInfo(int nNetWorkId, int nLevel)
	{
		WifiConfiguration wifiCfg = m_APMgr.getConnConfigInfoByNetWorkId(nNetWorkId);
		
		if (wifiCfg == null)
			return "";
		String strOut = "";
		strOut += "BSSID:";
		if (wifiCfg.BSSID != null)
			strOut += wifiCfg.BSSID;
		strOut += "\r\n";
		
		strOut += "SSID:";
		if (wifiCfg.SSID != null)
			strOut += wifiCfg.SSID;
		strOut += "\r\n";
		
		strOut += "加密类型:";
		String strKeyType = WifiHelper.getWifiConfigurationSecurity(wifiCfg); 
		strOut += strKeyType;
		strOut += "\r\n";
		strOut += "强度:";
		strOut += nLevel + "\r\n";
		return strOut;		
	}
}
